const app = getApp()
var that = ''
var firstKeyword
var firstscore
var firstroot

Page({
  data: {
    history: [],
    hot: [],
    dialogShow: false,
    garbage: null,
    isShow: false,
    image: 'cloud://cloud1-3g8hhsqrdb5adc66.636c-cloud1-3g8hhsqrdb5adc66-1318495870/pages_imge/search.jpg',
    base64Img: '',
    token: '',
    token_A: '',
    result: [],
    result_A: [],
    result_kind: [],
    uid: "c124bafd03ba4909b1f7794c3e38af32", //用户密钥，巴法云控制台获取
    myTopic: "mytrash", //图片上传的主题，图片云控制台创建
    num: 1, //获取的图片数量，可随意
    imgList: [], //存储图片地址和时间，用于前端展示
    img: [],
    picArr: [], //存储图片的地址，用于图片点击预览
    loading_status: true, //加载状态
  },

  time(time) { //时间戳转时间函数
    var date = new Date(parseInt(time) * 1000 + 8 * 3600 * 1000);
    return date.toJSON().substr(0, 19).replace('T', ' ');
  },

  getPicture() { //获取图片函数
    //api 接口详细说明见巴法云接入文档
    var that = this
    wx.request({
      url: 'https://images.bemfa.com/cloud/v1/get/', //获取图片接口，详见巴法云接入文档
      data: {
        uid: that.data.uid, //uid字段
        topic: that.data.myTopic, //topic字段
        num: that.data.num //num字段
      },
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      success(res) {
        var imgArr = [] //定义空数组，用于临时存储图片地址和时间
        var arr = [] //定义空数组，用于临时存储图片地址
        for (var i = 0; i < res.data.data.length; i++) { //遍历获取的结果数组
          var url = res.data.data[i].url //提取图片地址
          var time = that.time(url.substring(url.lastIndexOf("-") + 1, url.lastIndexOf("."))) //提取图时间
          imgArr.push({
            "url": url,
            "time": time
          }) //将存储图片地址和时间存入临时数组
          arr.push(url) //将存储图片地址存入临时数组
        }
        that.setData({ //把临时数组值复制给变量用于展示
          imgList: imgArr, //将临时存储图片地址和图片时间的数组赋值给用于图片预览的数组
          picArr: arr, //将临时存储图片地址的数组赋值给用于图片预览的数组
        })
        console.log(that.data.imgList) //打印赋值结果
        for (let i = 0; i < that.data.imgList.length; i++) {
          that.data.img = that.data.imgList[i];
        }
      }
    })
  },

  //图片转为base64
  getB64ByUrl(url) {
    wx.getFileSystemManager().readFile({
      filePath: url,
      encoding: 'base64',
      success: (res) => {
        this.setData({
          base64Img: res.data
        })
      }
    })
  },

  //获取垃圾桶图片
  imgSelect() {
    this.getPicture();
    this.setData({
      isShow: false
    })
    wx.downloadFile({
      url: that.data.img.url,
      success: (res) => {
        const tempFilePaths = res.tempFilePath
        console.log(that.data.img.url)
        this.getB64ByUrl(tempFilePaths)
        this.setData({
          image: tempFilePaths
        })
      }
    })
  },

  //选择本地图片
  local_select_img() {
    this.setData({
      isShow: false
    })
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths[0]
        this.getB64ByUrl(tempFilePaths)
        this.setData({
          image: tempFilePaths
        })
      }
    })
  },

  //识别
  getToken() {
    wx.showLoading({
      title: '识别中...',
    })
    wx.request({
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=1EIG9DGfBv3HszfXCokUUht4&client_secret=0gvG2BUwZ8D6lfkBMtLErxGsG0AsPtXc',
      success: (res) => {
        const token = res.data.access_token
        this.getResult(token)
      }
    })
  },

  //判断是否有图片
  plant() {
    if (!this.data.base64Img) {
      this.setData({
        isShow: true
      })
      return
    }
    this.getToken()
  },

  //图像识别
  getResult(token) {
    wx.request({
      url: 'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token=' + token,
      method: 'POST',
      data: {
        image: this.data.base64Img
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        this.setData({
          result: that.resultFilter(res.data.result)
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  //丢弃建议
  getToken_A() {
    if (!this.data.base64Img) {
      this.setData({
        isShow: true
      })
      return
    } else {
      // 判断加载状态
      var ls = this.data.loading_status
      this.setData({
        loading_status: !ls
      })
      console.log("判断是" + ls)
      const url_token = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Zr0exdXDxEOqWKm7m7tPucdj&client_secret=9sYsg6ORMAiuwx2q1OaEo37siFuqjvpO";
      wx.request({
        url: "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Zr0exdXDxEOqWKm7m7tPucdj&client_secret=9sYsg6ORMAiuwx2q1OaEo37siFuqjvpO",
        method: "POST",
        header: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        success: res => {
          const access_token = res.data.access_token
          //console.log("TOKEN:" + access_token)
          const url_chat = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + access_token
          const payload = {
            "messages": [{
              "role": "user",
              "content": "快速回答、简短、合理地回答我的问题：根据" + firstKeyword + "这个我丢弃的垃圾给我一些生活建议"
            }]
          };
          wx.request({
            url: url_chat,
            method: "POST",
            data: payload,
            header: {
              'Content-Type': 'application/json'
            },
            success: (res) => {
              //console.log(res.data, typeof (res.data));
              this.setData({
                result_A: res.data,
                loading_status: true
              })
            },
          });
        },
      });
    }
  },

  //result结果过滤
  resultFilter(arr) {
    if (!Array.isArray(arr)) {
      return arr
    }
    arr.forEach((item) => {
      item.score = (item.score.toFixed(4) * 100).toFixed(2) + '%'
      //console.log(typeof (item.score))
    })
    firstKeyword = arr[0].keyword
    let val = firstKeyword
    let devIntegral = app.deductionIntegral.get('garbageTextSearch')
    wx.cloud.callFunction({ //垃圾文字搜索
      name: 'api',
      data: {
        $url: "garbageTextSearch",
        text: val,
        devIntegral: devIntegral
      }
    }).then(res => { //然后执行：
      wx.hideLoading();
      let result = res.result
      if (result.code == 1) {
        this.setData({
          dialogShow: true,
          result_kind: result.data.recommendList[0].goodsType
        })
        console.log(that.data.result_kind)
        //减去分数
        app.globalData.userInfo.integral -= devIntegral
        app.$db.set('userInfo', app.globalData.userInfo)
      } else {
        wx.showToast({
          title: result.msg,
          icon: 'none',
          duration: 1500
        })
      }
      //添加到搜索历史
      if (this.data.history.indexOf(val) == -1) {
        if (this.data.history.length > 100) {
          this.data.history = this.data.history.shift()
        }
        this.setData({
          history: this.data.history.concat(val)
        })
        this.addHot(val)
        app.$db.set('history', this.data.history)
      }
    })
    firstroot = arr[0].root
    firstscore = arr[0].score
    console.log("识别为" + firstKeyword)
    return arr
  },

  getHot() {
    wx.cloud.callFunction({
      name: 'db',
      data: {
        $url: "getHot"
      }
    }).then(res => {
      let data = res.result.data
      let hot = data && data.map(item => item.hot_text)
      this.setData({
        hot: hot || []
      })
    })
  },
  addHot(hot_text) {
    wx.cloud.callFunction({
      name: 'db',
      data: {
        $url: "addHot",
        hot_text: hot_text
      }
    })
  },

  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    that = this;
    this.getPicture() //获取图片
    this.getHot()
  },
})